package com.hcss.sys.client.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.hcss.common.base.BaseClass;
import com.hcss.paging.constant.PagingConstant;
import com.hcss.paging.model.QuerySchema;
import com.hcss.sys.client.constant.HcChrgClientConstants;
import com.hcss.sys.client.model.HcChrgClient;
import com.hcss.sys.client.model.par.HcChrgClientPar;
import com.hcss.sys.client.model.vo.HcChrgClientVO;
import com.hcss.sys.client.service.HcChrgClientService;
import com.hcss.update.model.UpdateSchema;
import com.hcss.util.AjaxResult;
import com.hcss.util.BeanCopyUtil;
import com.hcss.util.EmptyUtil;
import com.hcss.util.ListUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;

/**
 * @描述: 客户表 功能模块
 * @作者: fangtao
 * @创建日期: 2020-09-18 14:29:21
 */
@Slf4j
@RestController
@RequestMapping("hcChrgClient")
public class HcChrgClientController {

	@Autowired
    private HcChrgClientService hcChrgClientService;


    /**
     * 查询使用的schema
     * 使用.withQueryFields(QueryType type, String... queryFileds)插入查询规则和查询字段
     */
    static QuerySchema querySchema = new QuerySchema( HcChrgClient.class);

	/**
	 * 更新插入的schema，用于鉴定数据的安全性
	 */
    static UpdateSchema updateSchema = new UpdateSchema( HcChrgClient.class, null, null);

	/**
	 * HcChrgClient数据列表页面
	 *
	 * @return
	 */
	@GetMapping("listPage")
	public ModelAndView listPage(){
		return new ModelAndView("/chrg/client/hcChrgClient-listPage");
	}

	/**
	 * 新增页面
	 * @return
	 */
	@GetMapping("/addorupdate")
	public ModelAndView addPage(){
		ModelAndView page = new ModelAndView("/chrg/client/hcChrgClient-addPage");
		return page;
	}

	/**
	 * 修改页面
	 * @param id
	 * @return
	 */
	@GetMapping("/addorupdate/{id}")
	public ModelAndView updatePage(@PathVariable("id") String id){
		ModelAndView page = new ModelAndView("/chrg/client/hcChrgClient-updatePage");
		HcChrgClientVO hcChrgClientVO = hcChrgClientService.selectComplexDataById(id);
		return page;
	}

	/**
	 * 详情页面
	 * @param id
	 * @return
	 */
	@GetMapping("/detail/{id}")
	public ModelAndView detail(@PathVariable("id") String id){
		ModelAndView page = new ModelAndView("/chrg/client/hcChrgClient-detailPage");
		return page;
	}
	
	/**
     * HcChrgClient分页数据接口
     *
     * @param model 带有查询参数的对象
     * @return
     */
	@RequestMapping("/list")
	public AjaxResult hcChrgClient( HcChrgClientVO model){
		try {
			if (model.getPagenation()) {
				model.setUserid(BaseClass.getSessionUserid());
				PageInfo< HcChrgClientVO > list = hcChrgClientService.queryComplexPagingData(model);
				return AjaxResult.getPageHelperTableResult(list);
			} else {
				List< HcChrgClientVO > list =  hcChrgClientService.queryComplexAllData(model);
				return AjaxResult.getSuccessResult(list);
			}
		} catch (Exception e) {
			log.error("客户数据查询出错，参数：" + model.toString(), e);
			return AjaxResult.getErrorResult(e.getMessage());
		}
	}
	
	/**
     * HcChrgClient 单个数据的获取
     * @param id HcChrgClient主键
     * @return
     */
	@GetMapping("/{id}")
	public AjaxResult getHcChrgClientById(@PathVariable("id") String id){
        HcChrgClient hcChrgClient = hcChrgClientService.selectByPK(id);
        return new AjaxResult(hcChrgClient);
	}
	
	/**
	 * HcChrgClient 的新增
	 * @param par
	 * @return
	 */
	@PostMapping
	public AjaxResult addHcChrgClient( HcChrgClientPar par) {
		if (!UpdateSchema.checkAddOrUpdate(par, updateSchema)) return AjaxResult.getMissingParamResult();
		try {
			HcChrgClient model = BeanCopyUtil.copyConvey(par, HcChrgClient.class);
			model.setOpId(BaseClass.getSessionUserid());
			model.setOpDate(new Date());
			hcChrgClientService.insertModel(model);
            return new AjaxResult();
		} catch (Exception e) {
            log.error("新增操作出错，参数：[{}] ", par.toString(), e);
			return AjaxResult.getErrorResult(e.getMessage());
		}
	}
	
	/**
	 * HcChrgClient 的修改
	 * @return
	 */
	@PutMapping("/{id}")
	public AjaxResult updateHcChrgClient(@PathVariable("id") String id, HcChrgClientPar par) {
		if (!UpdateSchema.checkAddOrUpdate(par, updateSchema)) return AjaxResult.getMissingParamResult();
		try {
			HcChrgClient model = BeanCopyUtil.copyConvey(par, HcChrgClient.class);
            hcChrgClientService.updateModel(model);
            // TODO setId
            return new AjaxResult();
		} catch (Exception e) {
            log.error("更新操作出错，参数：[{}]", par.toString(), e);
			return AjaxResult.getErrorResult(e.getMessage());
		}
    }
    
    /**
	 * 根据ids集合进行删除
	 * 使用默认的分割符号“,”
	 * @param ids
	 * @return
	 */
	@DeleteMapping("/{ids}")
	public AjaxResult deleteByIds(@PathVariable("ids") String ids){
		if (EmptyUtil.isHaveEmpty(ids)) return AjaxResult.getMissingParamResult();
		try {
			List<String> idList = ListUtil.convey(ListUtil.split(ids, PagingConstant.defaultSplit), String.class);
			hcChrgClientService.deleteByIdsAndSendCargo(idList);
            return new AjaxResult();
		} catch (Exception e) {
            log.error("批量删除出错，参数：[{}]",ids, e);
            return AjaxResult.getErrorResult(e.getMessage());
		}
	}

	/**
	 * 新增客户（新增并提交）
	 * @param model
	 * @return
	 */
	@PostMapping("/addClientVO")
	public AjaxResult addClientVO( HcChrgClientVO model) {
        //校验客户重复性
        if (!hcChrgClientService.checkClient(model)) {
            return AjaxResult.getErrorResult("客户已存在，请误重复提交！");
        }
		try {
            //新增
            model.setClientNcstatus( HcChrgClientConstants.CLIENTNCSTATUS.CLIENTNCSTATUS_99);//内场待审核状态
            model.setClientStatus( HcChrgClientConstants.CLIENTSTATUS.CLIENTSTATUS_99);//市场待审核状态
			model.setOpId(model.getUserid());
			model.setOpDate(new Date());
            hcChrgClientService.addClientVO(model);
            return new AjaxResult();
		} catch (Exception e) {
			log.error("客户新增出错，参数：[{}] ", model.toString(), e);
			return AjaxResult.getErrorResult(e.getMessage());
		}
	}

	/**
	 * 修改客户（并提交）
	 * @param model
	 * @return
	 */
	@PostMapping("/updateClientVO")
	public AjaxResult updateClientVO( HcChrgClientVO model) {
		if (EmptyUtil.isHaveEmpty(model.getId()) || EmptyUtil.isHaveEmpty(model.getUserid())) {
			return AjaxResult.getMissingParamResult();
		}
        //校验客户重复性
        if (!hcChrgClientService.checkClient(model)) {
            return AjaxResult.getErrorResult("客户已存在，请误重复提交！");
        }
		try {
            //修改
            if ((!EmptyUtil.isHaveEmpty(model.getClientStatus()))
                    && HcChrgClientConstants.CLIENTSTATUS.CLIENTSTATUS_02.equals(model.getClientStatus())) {
                model.setClientStatus( HcChrgClientConstants.CLIENTSTATUS.CLIENTSTATUS_99);//待审核
            } else if ((!EmptyUtil.isHaveEmpty(model.getClientNcstatus()))
                    && HcChrgClientConstants.CLIENTNCSTATUS.CLIENTNCSTATUS_02.equals(model.getClientNcstatus())) {
                model.setClientNcstatus( HcChrgClientConstants.CLIENTNCSTATUS.CLIENTNCSTATUS_99);//待审核
            }
			model.setOpDate(new Date());
			model.setOpId(BaseClass.getSessionUserid());
            hcChrgClientService.updateClientVO(model);
            return new AjaxResult();
		} catch (Exception e) {
			log.error("客户修改出错，参数：[{}] ", model.toString(), e);
			return AjaxResult.getErrorResult(e.getMessage());
		}
	}

	/**
	 * 绑定
	 * @param model
	 * @return
	 */
	@PostMapping("/uAgentCarrier")
	public AjaxResult uAgentCarrier( HcChrgClientVO model) {
		if (EmptyUtil.isHaveEmpty(model.getId(),model.getClientType())) return AjaxResult.getMissingParamResult();
		try {
			hcChrgClientService.uAgentCarrier(model);
			//关联结果返回货代
			HcChrgClientVO hcChrgClientVO  = hcChrgClientService.selectComplexDataById(model.getId());
			return new AjaxResult();
		} catch (Exception e) {
			log.error("结算绑定出错，参数：[{}]",model, e);
			return AjaxResult.getErrorResult(e.getMessage());
		}
	}

	/**
	 * 通过客户id获取关联的航司货代信息
	 * @param id
	 * @return
	 */
	@GetMapping("/getAgentcarrier")
	public AjaxResult getAgentcarrierByCid(String id){
		if (EmptyUtil.isHaveEmpty(id)) return AjaxResult.getMissingParamResult();
		try {
			HcChrgClientVO model=hcChrgClientService.getAgentcarrier(id);
			return new AjaxResult(model);
		} catch (Exception e) {
			log.error("获取客户货代航司出错，参数：[{}]",id, e);
			return AjaxResult.getErrorResult(e.getMessage());
		}
	}

	/**
	 * 校验客户数据
	 */
	@PostMapping("/checkClientData")
	public AjaxResult checkClientData( HcChrgClientVO model) {
		try {
			//校验客户数据
			hcChrgClientService.checkClientData(model);
			return new AjaxResult();
		} catch (Exception e) {
			log.error("客户注册出错，参数：[{}] ", model.toString(), e);
			return AjaxResult.getErrorResult(e.getMessage());
		}
	}
}